<template>
  <div class="performance-list">
    <el-card>
      <!-- 演出详情/编辑/创建对话框 -->
      <PerformanceDialog
        v-if="dialogVisible"
        :visible="dialogVisible"
        :mode="dialogMode"
        :performance-data="currentPerformance"
        @close="handleDialogClose"
        @success="handleDialogSuccess"
      />

      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <div class="header-left">
          <h2>演出管理</h2>
          <p class="description">管理音乐节演出信息，包括演出安排、场地、时间等</p>
        </div>
        <div class="header-right">
          <el-button 
            v-if="userStore.hasPermission(ALL_PERMISSIONS.PERFORMANCE_CREATE)"
            type="primary" 
            @click="showCreateDialog"
          >
            <el-icon><Plus /></el-icon>
            添加演出
          </el-button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="搜索演出标题、描述等"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="已安排" value="SCHEDULED" />
              <el-option label="进行中" value="ONGOING" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
            </el-select>
          </el-form-item>
          <el-form-item label="演出日期">
            <el-date-picker
              v-model="searchForm.date"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="场地">
            <el-select
              v-model="searchForm.venueId"
              placeholder="选择场地"
              clearable
              filterable
              style="width: 250px"
            >
              <el-option
                v-for="venue in venueList"
                :key="venue.id"
                :label="`${venue.name} (${venue.city})`"
                :value="venue.id"
              >
                <div class="venue-option">
                  <div class="venue-name">{{ venue.name }}</div>
                  <div class="venue-details">
                    <span class="venue-city">{{ venue.city }}</span>
                    <span v-if="venue.capacity" class="venue-capacity">{{ venue.capacity }}人</span>
                    <span class="venue-sort">排序: {{ venue.sortOrder }}</span>
                  </div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="场地排序">
            <el-select
              v-model="searchForm.venueSortBy"
              placeholder="选择排序字段"
              style="width: 150px"
              @change="handleVenueSortChange"
            >
              <el-option label="按排序值" value="sortOrder" />
              <el-option label="按名称" value="name" />
              <el-option label="按城市" value="city" />
              <el-option label="按创建时间" value="createdAt" />
            </el-select>
            <el-select
              v-model="searchForm.venueSortOrder"
              placeholder="排序方向"
              style="width: 100px; margin-left: 8px"
              @change="handleVenueSortChange"
            >
              <el-option label="升序" value="asc" />
              <el-option label="降序" value="desc" />
            </el-select>
            <el-button
              type="info"
              size="small"
              style="margin-left: 8px"
              @click="refreshVenues"
            >
              刷新场地
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 演出列表 -->
      <el-table
        v-loading="loading"
        :data="performanceList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="艺人" width="120">
          <template #default="{ row }">
            <div class="artist-info">
              <el-avatar 
                :src="row.artist?.avatar" 
                :size="30"
                :icon="UserFilled"
              />
              <span class="artist-name">{{ row.artist?.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="演出标题" min-width="150" />
        <el-table-column label="时间" width="200">
          <template #default="{ row }">
            <div class="time-info">
              <div>{{ formatDate(row.startTime, 'MM-DD HH:mm') }}</div>
              <div class="time-duration">{{ formatDate(row.endTime, 'HH:mm') }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="场地" width="120">
          <template #default="{ row }">
            <div class="venue-info">
              <span class="venue-name">{{ row.venue?.name || '未知场地' }}</span>
              <span v-if="row.venue?.city" class="venue-city">({{ row.venue.city }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排序优先级" width="100">
          <template #default="{ row }">
            <div v-if="row.venue?.sortOrder !== undefined" class="sort-priority">
              <el-tag 
                :type="getSortPriorityType(row.venue.sortOrder)"
                size="small"
              >
                {{ row.venue.sortOrder }}
              </el-tag>
              <span class="sort-desc">优先级</span>
            </div>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="楼层" width="80">
          <template #default="{ row }">
            <span v-if="row.floorRef?.name">{{ row.floorRef.name }}</span>
            <span v-else-if="row.floor">{{ row.floor }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="容量" width="100">
          <template #default="{ row }">
            <span v-if="row.maxCapacity">{{ row.maxCapacity }}人</span>
            <span v-else class="text-muted">不限</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.PERFORMANCE_READ)"
              size="small" 
              @click="viewPerformance(row)"
            >
              查看
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.PERFORMANCE_UPDATE)"
              size="small" 
              type="primary" 
              @click="editPerformance(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.PERFORMANCE_DELETE)"
              size="small" 
              type="danger" 
              @click="deletePerformance(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
                  :current-page="pagination.page"
        :page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UserFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import { performanceApi } from '@/api'
import { clientVenueApi } from '@/api/clientVenue'
import type { Performance, Venue } from '@/types'
import PerformanceDialog from './components/PerformanceDialog.vue'
import { formatDate } from '@/utils/format'

// 客户端场馆数据接口
interface ClientVenueData {
  id: number
  name: string
  description?: string
  address: string
  city: string
  country: string
  capacity?: number
  status: 'ACTIVE' | 'INACTIVE' | 'MAINTENANCE'
  sortOrder: number
  createdAt: string
  updatedAt: string
  floorCount: number
  performanceCount: number
}

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const performanceList = ref<Performance[]>([])
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const searchForm = reactive({
  search: '',
  status: '',
  date: '',
  venueId: undefined as number | undefined,
  venueSortBy: 'sortOrder' as 'sortOrder' | 'name' | 'createdAt' | 'city',
  venueSortOrder: 'asc' as 'asc' | 'desc'
})

// 场地列表
const venueList = ref<ClientVenueData[]>([])

// 获取场地列表
const fetchVenues = async () => {
  try {
    const response = await clientVenueApi.getList({
      sortBy: searchForm.venueSortBy,
      sortOrder: searchForm.venueSortOrder
    })
    venueList.value = response.data.venues
  } catch (error) {
    ElMessage.error('获取场地列表失败')
  }
}

// 获取演出列表
const fetchPerformances = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      limit: pagination.limit,
      ...searchForm
    }
    // 确保venueId是数字类型
    if (params.venueId !== undefined) {
      params.venueId = Number(params.venueId)
    }
    const response = await performanceApi.getList(params)
    performanceList.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    ElMessage.error('获取演出列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchPerformances()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    status: '',
    date: '',
    venueId: undefined,
    venueSortBy: 'sortOrder',
    venueSortOrder: 'asc'
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchPerformances()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchPerformances()
}

const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const currentPerformance = ref<Performance | null>(null)

// 显示创建对话框
const showCreateDialog = () => {
  dialogMode.value = 'create'
  currentPerformance.value = {} as Performance
  dialogVisible.value = true
}

// 编辑演出
const editPerformance = (performance: Performance) => {
  dialogMode.value = 'edit'
  currentPerformance.value = { ...performance }
  dialogVisible.value = true
}

// 查看演出详情
const viewPerformance = async (performance: Performance) => {
  dialogMode.value = 'view'
  try {
    const response = await performanceApi.get(performance.id)
    currentPerformance.value = response.data
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取演出详情失败')
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  currentPerformance.value = null
}

const handleDialogSuccess = () => {
  handleDialogClose()
  fetchPerformances()
}

// 删除演出
const deletePerformance = async (performance: Performance) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除演出 "${performance.title}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await performanceApi.delete(performance.id)
    ElMessage.success('删除成功')
    fetchPerformances()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'SCHEDULED': 'primary',
    'ONGOING': 'success',
    'COMPLETED': 'info',
    'CANCELLED': 'danger'
  }
  return statusMap[status] as any || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'SCHEDULED': '已安排',
    'ONGOING': '进行中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 获取排序优先级类型
const getSortPriorityType = (sortOrder: number) => {
  if (sortOrder === 0) {
    return 'info' // 默认或低优先级
  } else if (sortOrder === 1) {
    return 'success' // 高优先级
  } else {
    return 'warning' // 其他优先级
  }
}

// 场地排序变化处理
const handleVenueSortChange = () => {
  pagination.page = 1 // 排序变化时重置到第一页
  fetchPerformances()
}

// 刷新场地列表
const refreshVenues = () => {
  fetchVenues()
}

// 初始化
onMounted(() => {
  fetchVenues()
  fetchPerformances()
})
</script>

<style scoped>
.performance-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.artist-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.artist-name {
  font-size: 14px;
  color: #303133;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-duration {
  font-size: 12px;
  color: #909399;
}

.text-muted {
  color: #909399;
  font-style: italic;
}

.venue-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.venue-name {
  font-weight: 500;
  color: #303133;
}

.venue-city {
  font-size: 12px;
  color: #909399;
}

.venue-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.venue-details {
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 8px;
}

.venue-capacity {
  font-weight: 500;
  color: #409eff; /* A primary color for capacity */
}

.venue-sort {
  font-weight: 500;
  color: #67c23a; /* A success color for sort order */
}

.sort-priority {
  display: flex;
  align-items: center;
  gap: 4px;
}

.sort-desc {
  font-size: 12px;
  color: #909399;
}
</style>